import React, { Component } from "react";
import { RadioButtonGroupInput, required } from "react-admin";
import { GraphQLClient } from "graphql-request";
import settings from "../../settings";

const graphqlClient = new GraphQLClient(`${settings.Prisma.endpoint}`);
const DELIMITER = "#";

class CertStatusRadioButtonGroupInput extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: null,
        };
    }

    handleChange = (e) => {
        const trueString = e[0]+e[1]+e[2]+e[3];
        if (trueString === "true") {
            this.setState({ status: true });
            this.props.handleChange(true);
        } else {
            this.setState({ status: false });
            this.props.handleChange(false);
        }
    }

    componentDidMount() {
        const { ownerCreditCode, name } = this.props.record;
        const creditCodeCombineName = `${ownerCreditCode}${DELIMITER}${name}`;
        graphqlClient.request(`
            {
               cert(where: {
                   creditCodeCombineName: "${creditCodeCombineName}"
               }){
                   status
               }
            }
        `).then((res) => {
            if (res.cert) { 
                this.setState({ status: res.cert.status }); 
                this.props.handleChange(res.cert.status);
            }
        });
    }

    render() {
        const { status } = this.state;
        return (
            status === null
                ? null 
                : <RadioButtonGroupInput
                    label="证书启用状态"
                    choices={[
                        { id: "true", name: "启用" },
                        { id: "false", name: "禁用" },
                    ]}
                    validate={required()}
                    onChange={this.handleChange}
                    {...this.props}
                    defaultValue={status ? "true" : "false"}
                />
        );
    }
}

export default CertStatusRadioButtonGroupInput;